//
//  HMReturnGoodViewController.m
//  HMMarket
//
//  Created by haohao on 2017/6/28.
//  Copyright © 2017年 homai. All rights reserved.
//

#define rowHeight 49
#define marin 20

#import "HMReturnGoodViewController.h"

#import "HMSelectApplyGoodTableViewCell.h"
#import "HMApplyMoneyTableViewCell.h"
#import "HMApplyFhotoTableViewCell.h"
#import "HMApplyReasonTableViewCell.h"
#import "HMSelectApplyGoodTableViewCell.h"
#import "HMApplyForReasonTableViewCell.h"
#import "OrderModel.h"
#import "HMApplyCancleFhotoTableViewCell.h"
#import "HMOrderController.h"
#import "HMReturnSaleModel.h"
#define cellWidth (KWidthSCREEN - marin * 4) / 3 + 10

@interface HMReturnGoodViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate>

@property (nonatomic, strong) HMReturnSaleModel *saleModel;

@end

@implementation HMReturnGoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpSubView];
    // Do any additional setup after loading the view from its nib.
}

- (void)setUpSubView {
    self.title = @"退货中";
    
    _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 48 - 64) style:UITableViewStyleGrouped];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.separatorColor = [UIColor clearColor];
    _myTableView.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    [self.view addSubview:_myTableView];
    
    UIButton *submit = [UIButton buttonWithType:UIButtonTypeCustom];
    [submit setTitle:@"撤销申请" forState:UIControlStateNormal];
    submit.titleLabel.font = [UIFont systemFontOfSize:16.0];
    submit.frame = CGRectMake(0, KHeightSCREEN - 48, KWidthSCREEN, 48);
    [submit setBackgroundColor:kMainColor];
    [submit addTarget:self action:@selector(cancelApply) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submit];
    
    [self.myTableView registerNib:[UINib nibWithNibName:@"HMSelectApplyGoodTableViewCell" bundle:nil] forCellReuseIdentifier:@"HMSelectApplyGoodTableViewCell"];
    [self getData];
}

- (void)getData {
    [HttpBaseTool post:kGetReturnOrder params:@{@"oid":_model.oid} success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue] == 200) {
            _saleModel = [HMReturnSaleModel mj_objectWithKeyValues:responseObj[@"data"]];
            [self.imageArray addObject:[HMReductionData replaceNullValue:_saleModel.pic0]];
            [self.imageArray addObject:[HMReductionData replaceNullValue:_saleModel.pic1]];
            [self.imageArray addObject:[HMReductionData replaceNullValue:_saleModel.pic2]];
            [_myTableView reloadData];
        } else {
            [HMHUDManager showHUDWithText:responseObj[@"msg"]];
        }
    } failure:^(NSError *error) {
        
    }];

    
}

- (void)cancelApply {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认要撤销申请吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HttpBaseTool post:kUpdateOrderByoid params:@{@"id":_saleModel.oid} success:^(id responseObj) {
            if ([responseObj[@"code"] integerValue] == 200) {
                OrderRefresh;
                [HMHUDManager showHUDWithText:@"申请成功，请耐心等待客服处理"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            } else {
                [HMHUDManager showHUDWithText:responseObj[@"msg"]];
            }
        } failure:^(NSError *error) {
            
        }];
    }];
    [alert addAction:cancle];
    [alert addAction:sure];
    [self.navigationController presentViewController:alert animated:YES completion:nil];
 
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_saleModel.pic0.length == 0 &&_saleModel.pic0.length == 0 && _saleModel.pic0.length == 0) {
        return 3;
    } else {
        return 4; 
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *indetifi = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indetifi];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indetifi];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"  %@", _saleModel.item_name];
        cell.textLabel.textColor = kc9c9c9;
        return cell;
    } else if (indexPath.section == 1) {
        HMApplyMoneyTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMApplyMoneyTableViewCell" owner:self options:nil] firstObject];
        cell.totalLabel.hidden = YES;
        cell.moneyLabel.userInteractionEnabled = NO;
        cell.returnMoney = [NSString stringWithFormat:@"%@", _saleModel.price];
        return cell;
    } else if (indexPath.section == 2) {
        HMApplyForReasonTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMApplyForReasonTableViewCell" owner:self options:nil] firstObject];
        cell.applyString = _saleModel.content;
        return cell;
    } else if (indexPath.section == 3) {
        static NSString *identi = @"HMApplyCancleFhotoTableViewCell";
        HMApplyCancleFhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identi];
        if (cell == nil) {
            cell = [[HMApplyCancleFhotoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identi];
        }
        cell.imageArray = self.imageArray;
        return cell;
    } else {
        return nil;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        CGRect rect = [self returnRectWithString:_saleModel.content width:KWidthSCREEN - 40];
        if (rect.size.height < rowHeight) {
            return rowHeight;
        } else {
            return rect.size.height + 10;
        }
    } else if (indexPath.section == 3){
        return (KWidthSCREEN - 20 * 4) / 3 + 10;
    } else {
        return rowHeight;
    }
}

- (CGRect)returnRectWithString:(NSString *)string width:(float)width{
    MyLog(@"width = %f", width);
    CGRect nameRect = [string boundingRectWithSize:CGSizeMake(width, 0)/*计算宽度时要确定高度*/ options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0f]} context:nil];
    return nameRect;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidthSCREEN, rowHeight)];
    
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(marin, 0, KWidthSCREEN - marin, rowHeight)];
    [titleView addSubview:headerLabel];
    
    //    NSDictionary *attrDict1 = @{ NSForegroundColorAttributeName: [UIColor redColor] };
    if (section == 0) {
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"*退货商品"];
        [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
        headerLabel.attributedText = AttributedStr;
        return titleView;
    } else if (section == 2){
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"*退货原因"];
        [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
        headerLabel.attributedText = AttributedStr;
        return titleView;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return rowHeight;
        
    } else if (section == 2){
        return rowHeight;
    } else {
        return 10;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSMutableArray *)imageArray {
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

@end
